package cn.com.zetatech.maple.core.local;

import cn.com.zetatech.maple.entity.FtpDFile;
import cn.com.zetatech.maple.local.LocalHandler;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 本地处理器:
 * 将连续的N行合并为一行
 */
public class LocalMergeLines implements LocalHandler {
    /**
     * 连续的N行，N
     */
    @Setter
    @Getter
    private String mergeSize = "2";

    /**
     * 对于待合并的N行，合并时候连接行一行的符号，默认为空字符串,即不添加任何连接符号
     */
    @Setter
    @Getter
    private String mergeStr = "";

    @Override
    public void handle(FtpDFile dFile) throws IOException {
        String localFile = dFile.getLocal();
        File f = new File(localFile);
        List<String> rawLines = FileUtils.readLines(f, StandardCharsets.UTF_8);
        if (rawLines.size() % Integer.valueOf(this.mergeSize) != 0) {
            throw new RuntimeException("file can not be merged for file's lines: " + rawLines.size() + ",merge size:" + mergeSize);
        }
        List<List<String>> parts = Lists.partition(rawLines, Integer.valueOf(this.mergeSize));
        List<String> result = new ArrayList<>(parts.size());

        for (List<String> part : parts) {
            String mergedLine = Joiner.on(mergeStr).join(part);
            result.add(mergedLine);
        }
        FileUtils.writeLines(f, StandardCharsets.UTF_8.name(), result);
    }
}

